import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

// 路由器主类（定义为公共类）
public class Router {
    public Router() {
        this.routes = new ArrayList<>();
    }

    public void addRoute(String method, String path, RequestHandler handler) {
        Route route = new Route(method, path, handler);
        routes.add(route);
        System.out.println("添加路由规则： [" + method + "] ->" + path);
    }

    public RouteMatch findRoute(String method, String path) {
        for (Route route : routes) {
            RouteMatch match = route.matches(method, path);
            if (match != null) {
                System.out.println("匹配路由规则： [" + method + "] ->" + route.getPathPattern());
                return match;
            }
        }
        return null;
    }

    // 存储匹配结果
    public static class RouteMatch {
        public RouteMatch(RequestHandler handler) {
            this.handler = handler;
            this.pathParameters = new HashMap<>();
        }

        public void addPathParameter(String name, String value) {
            pathParameters.put(name, value);
        }

        public RequestHandler getHandler() {
            return handler;
        }

        public Map<String, String> getPathParameters() {
            return pathParameters;
        }

        private final RequestHandler handler;             // 请求处理器
        private final Map<String, String> pathParameters; // 存储路径参数
    }

    // 具体的路由规则
    public static class Route {
        public Route(String method, String pathPattern, RequestHandler handler) {
            this.method = method.toUpperCase();
            this.handler = handler;
            this.parameterNames = new ArrayList<>();
            this.pattern = compilePattern(pathPattern);
            this.pathPattern = pathPattern;
        }

        private Pattern compilePattern(String pathPattern) {
            if (pathPattern == "/") return Pattern.compile("^/$");

            // 拼接 模式匹配规则 字符串
            StringBuilder regex = new StringBuilder("^"); // 构建正则表达式，^表示字符串开始
            String[] parts = pathPattern.split("/");

            for (String part : parts) {
                if (part.startsWith("{") && part.endsWith("}")) {
                    // 参数
                    String paramName = part.substring(1, part.length() - 1);
                    parameterNames.add(paramName);
                    regex.append("/([^/]+)");
                } else if (!part.isEmpty()) {
                    // 路径
                    regex.append("/").append(part);
                }
            }
            regex.append("$"); // $表示模式行尾结束

            return Pattern.compile(regex.toString());
        }

        public RouteMatch matches(String method, String path) {
            if (!this.method.equals(method.toUpperCase())) {
                return null;
            }

            // 获取匹配器
            Matcher matcher = pattern.matcher(path);
            if (matcher.matches()) {
                RouteMatch routeMatch = new RouteMatch(this.handler);
                // 根据 匹配器 提取 对应参数
                for (int i = 0; i < parameterNames.size(); i++) {
                    String paramValue = matcher.group(i + 1);
                    routeMatch.addPathParameter(parameterNames.get(i), paramValue);
                }
                return routeMatch;
            }
            return null;
        }

        public String getPathPattern() {
            return pathPattern;
        }

        private final String method;               // 路由 HTTP 方法
        private final List<String> parameterNames; // 路径参数名
        private final Pattern pattern;             // 根据 路由匹配规则 编译的 正则模板对象（线程安全）
        private final String pathPattern;          // 路由匹配规则
        private final RequestHandler handler;      // 该路由规则下的业务处理器
    }

    // 路由表
    private final List<Route> routes;
}
